package com.tzstcl.framework.shiro;

import com.tzstcl.framework.constants.AppConstants;
import com.tzstcl.sys.user.model.SysDept;
import com.tzstcl.sys.user.model.SysPost;
import com.tzstcl.sys.user.model.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;

/**
 * shiro 工具类
 *
 * @author haocj
 */
public class ShiroUtils {

    public static Subject getSubjct() {
        return SecurityUtils.getSubject();
    }

    public static Session getSession() {
        if(null==SecurityUtils.getSubject()){
            return null;
        }
        return SecurityUtils.getSubject().getSession();
    }

    public static void logout() {
        getSubjct().logout();
    }

    public static SysUser getUser() {
        try {
            SysUser user = (SysUser) getSubjct().getPrincipal();
            if (user != null) {
                return user;
            }
        } catch (Exception e) {

        }

        return null;
    }

    public static void setUser(SysUser user) {
        Subject subject = getSubjct();
        PrincipalCollection principalCollection = subject.getPrincipals();
        String realmName = principalCollection.getRealmNames().iterator().next();
        PrincipalCollection newPrincipalCollection = new SimplePrincipalCollection(user, realmName);
        // 重新加载Principal
        subject.runAs(newPrincipalCollection);
    }

    public static void clearCachedAuthorizationInfo() {
        RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        UserRealm realm = (UserRealm) rsm.getRealms().iterator().next();
        realm.clearCachedAuthorizationInfo();
    }

    public static Long getUserId() {
        return getUser().getId();
    }


    public static SysDept getDept() {
        return getUser().getDept();
    }

    public static String getLoginName() {
        return getUser().getLoginName();
    }

    public static String getIp() {
        return getSubjct().getSession().getHost();
    }

    public static String getSessionId() {
        return String.valueOf(getSubjct().getSession().getId());
    }

    public static SysPost getPost() {
        return getUser().getPost();
    }

    public static boolean adminLogin(String loginName) {
        if (AppConstants.SUPER_ADMIN_Name.equals(loginName)) {
            return true;
        } else {
            return false;
        }
    }
}
